﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using MySql.Data.MySqlClient;

namespace VehicleMaintenance.Comm
{
	public class DataBaseComm
	{
		public static string CreatDataBase()
		{
			string info = "";

			string strSQL = "CREATE DATABASE `car` DEFAULT CHARACTER SET gbk";

			MySqlConnection con = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CarDBForCreat"].ConnectionString);
			try
			{
				con.Open();
				MySqlCommand com = new MySqlCommand(strSQL, con);
				if (com.ExecuteNonQuery() > 0)
				{
					info += "数据库创建成功。";
				}
				else
				{
					info += "数据库创建失败。";
				}

				string bakFile = Path.Combine(Application.StartupPath, "Car_Empty.bak");
				if (!File.Exists(bakFile))
				{
					info += "\r\n数据表创建失败，因为数据表创建文件不存在。";
				}
				else
				{
					Restore(bakFile);
					info += "\r\n数据库表创建成功，请用内置用户admin登录";
				}

				return info;
			}
			catch (Exception ex)
			{
				return ex.Message;
			}
			finally
			{
				con.Close();
			}

		}

		//备份：mysqldump -hlocalhost -P3306 -uroot -p123 --default-character-set=utf8 mydata > d:\test\mydata.sql
		//还原：mysql -hlocalhost -P3306 -uroot -p123 mydata  < d:\test\mydata.sql

		public static void Backup()
		{
			try
			{
				//String command = "mysqldump --quick --host=localhost --default-character-set=gb2312 --lock-tables --verbose  --force --port=端口号 --user=用户名 --password=密码 数据库名 -r 备份到的地址";

				//构建执行的命令
				StringBuilder sbcommand = new StringBuilder();

				StringBuilder sbfileName = new StringBuilder();
				sbfileName.AppendFormat("{0}-{1}.{2}", "Car", DateTime.Now.ToString("yyyy-MM-dd-HH"), "bak");
				String fileName = sbfileName.ToString();

				SaveFileDialog saveFileDialog = new SaveFileDialog();
				saveFileDialog.AddExtension = true;
				saveFileDialog.CheckFileExists = false;
				saveFileDialog.CheckPathExists = false;
				saveFileDialog.Filter = "备份文件 (*.bak)|*.bak";
				saveFileDialog.FilterIndex = 0;
				saveFileDialog.DefaultExt = "bak";
				saveFileDialog.FileName = fileName;

				if (saveFileDialog.ShowDialog() == DialogResult.OK)
				{
					String directory = saveFileDialog.FileName;

					sbcommand.AppendFormat("mysqldump -hlocalhost -P3306 -uroot -proot2232364 --default-character-set=gbk car > \"{0}\"", directory);
					String command = sbcommand.ToString();

					//获取mysqldump.exe所在路径
					String appDirecroty = Application.StartupPath + "\\";
					Cmd.StartCmd(appDirecroty, command);
					MessageBox.Show(@"数据库已成功备份到 " + directory + " 文件中", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				}

			}
			catch (Exception ex)
			{
				MessageBox.Show("数据库备份失败！" + ex.Message);

			}
		}

		//还原方法，调用的是mysql自带工具mysql，还原时要注意的是选择的文件所在路径时，文件名要是有空格的话会出
		//异常，所以在文件路径名加上双引号""
		public static void Restore(string file)
		{

			//string s = "mysql --port=端口号 --user=用户名 --password=密码 数据库名<还原文件所在路径";

			try
			{
				StringBuilder sbcommand = new StringBuilder();
				String directory = file;

				if (directory.Length == 0)
				{
					OpenFileDialog openFileDialog = new OpenFileDialog();
					openFileDialog.Filter = "备份文件 (*.bak)|*.bak";
					openFileDialog.FilterIndex = 0;
					openFileDialog.DefaultExt = "bak";

					if (openFileDialog.ShowDialog() == DialogResult.OK)
					{
						directory = openFileDialog.FileName;
					}
					else
					{
						return;
					}
				}
				//在文件路径后面加上""避免空格出现异常
				sbcommand.AppendFormat("mysql -hlocalhost -P3306 -uroot -proot2232364 --default-character-set=gbk car <\"{0}\"", directory);
				String command = sbcommand.ToString();

				//获取mysql.exe所在路径
				String appDirecroty = Application.StartupPath + "\\";

				if (file.Length == 0)
				{
					DialogResult result = MessageBox.Show("您是否真的想覆盖以前的数据库吗？那么以前的数据库数据将丢失！！！", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

					if (result == DialogResult.Yes)
					{
						Cmd.StartCmd(appDirecroty, command);
						MessageBox.Show("数据库还原成功！");
					}
				}
				else
				{
					Cmd.StartCmd(appDirecroty, command);
				}
			}


			catch (Exception ex)
			{
				MessageBox.Show("数据库还原失败！" + ex.Message);
			}

		}
	}

	public class Cmd
	{
		/// <summary>
		/// 执行Cmd命令
		/// </summary>
		/// <param name="workingDirectory">要启动的进程的目录</param>
		/// <param name="command">要执行的命令</param>
		public static void StartCmd(String workingDirectory, String command)
		{
			Process p = new Process();
			p.StartInfo.FileName = "cmd.exe";
			p.StartInfo.WorkingDirectory = workingDirectory;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardInput = true;
			p.StartInfo.RedirectStandardOutput = true;
			p.StartInfo.RedirectStandardError = true;
			p.StartInfo.CreateNoWindow = true;
			p.Start();
			p.StandardInput.WriteLine(command);
			p.StandardInput.WriteLine("exit");
		}
	}
}



